//
//  ViewController.swift
//  002.拖动回弹效果的实现（拖放后自动归位）
//
//  Created by Gao on 17/2/16.
//  Copyright © 2017年 Odm. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    //拖动的view
    @IBOutlet weak var myView: UIView!
    //拖动view的上约束
    @IBOutlet weak var myViewTopLayoutConstraint: NSLayoutConstraint!
    //拖动手势
    @IBOutlet var panGesture: UIPanGestureRecognizer!
    
    
    //保存初始时拖动view上约束的值
    var myViewTopLayoutConstant: CGFloat!
    //保存初始时拖动view的y坐标值
    var myViewOriginY: CGFloat!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加拖动手势响应
        panGesture.addTarget(self, action: #selector(ViewController.pan))
        //保存初始时拖动view上约束的值（用于后面还原）
        myViewTopLayoutConstant = myViewTopLayoutConstraint.constant
    }
    
    //拖动手势
    func pan() {
        //拖动开始
        if panGesture.state == .began {
            myViewOriginY = myView.frame.origin.y
        }
            
            //拖动过程
        else if panGesture.state == .changed {
            let y = panGesture.translation(in: self.view).y
            myViewTopLayoutConstraint.constant = myViewTopLayoutConstant + y
        }
            
            //拖动结束
        else if panGesture.state == .ended {
            //回弹
            UIView.animate(withDuration: 0.4, delay: 0, options: .curveEaseInOut, animations: {
                () -> Void in
                self.myView.frame.origin.y = self.myViewOriginY
            }, completion: { (success) -> Void in
                if success {
                    //回弹动画结束后恢复默认约束值
                    self.myViewTopLayoutConstraint.constant = self.myViewTopLayoutConstant
                }
            })
            return
        }
    }
    
    
    
    
}

